<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :minHeight="150"
    okText="移动"
    @register="register"
    :loading="loading"
    :title="modalTitle"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';
  import { computed, nextTick, ref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getnode, updateDriverInfo, getDriverInfo } from '/@/api/tag/index';

  const props = defineProps({
    formType: {
      type: Object,
      default: () => {},
    },
  });
  let loading = ref(false);
  let driverInfo = {};
  let modalTitle = computed(() => {
    return `移动设备`;
  });
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'nodeName',
      component: 'Select',
      label: '节点名称：',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '请选择节点',
        options: [],
        fieldNames: { label: 'label', value: 'value', key: 'key' },
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择节点');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
  ];

  const [registerForm, { validateFields, resetFields, clearValidate, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const emit = defineEmits(['submitSuccess']);
  const [register] = useModal();
  // 获取驱动信息

  async function getDriverInfoFn() {
    driverInfo = await getDriverInfo([props.formType.id]);
  }
  async function handleSubmint() {
    try {
      let res = await validateFields();
      driverInfo.nodeKey = res.nodeName;
      await updateDriverInfo([props.formType.id, driverInfo]);
      createMessage.success(t('layout.setting.operatingTitle'));
      emit('submitSuccess', {});
    } catch (error: any) {
      console.log('not passing', error);
    }
  }
  // 获取节点
  async function getnodeFn() {
    loading.value = true;
    try {
      let res = await getnode();
      let list = (Array.isArray(res) ? res : []).map((item) => {
        return {
          label: item.Name,
          value: item.Key,
          key: item.Key,
          disabled: item.Key === driverInfo.NodeKey,
        };
      });

      nextTick(() => {
        updateSchema({
          field: 'nodeName',
          componentProps: {
            options: list || [],
          },
        });
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  function handleVisibleChange(visible) {
    if (visible) {
      nextTick(async () => {
        await getDriverInfoFn();
        await getnodeFn();
        clearValidate();
      });
    } else {
      resetFields();
    }
  }
</script>

<style lang="less" scoped>
  .slot-select {
    width: 100%;
    height: 32px;
    padding: 0 11px;
    display: flex;
    position: relative;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
    cursor: pointer;
  }

  .slot-select:hover {
    border: 1px solid #1e80ff;
  }

  .slot-select-con {
    margin-right: 18px;
    line-height: 30px;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #000000d9;
    font-size: 14px;
  }

  .con-placeholder {
    color: #bfbfbf;
  }

  .icon-style {
    line-height: 30px;
    font-size: 11px;

    color: #bfbfbf;
  }

  .erro-style {
    border: 1px solid #ed6f6f !important;
  }

  .slot-select-diabled {
    background: #f5f5f5;
    cursor: not-allowed;

    .slot-select-con {
      color: rgba(0, 0, 0, 0.25);
    }
  }

  .slot-select-diabled:hover {
    border: 1px solid #d9d9d9;
  }
</style>
